// Global Vars
// Load Gmaps API
var map;
var bounds;
var markers = [];
var icons = [];
var sidebarDiv;
var g_addr;
var g_point = [];
var g_avatar;
var viewer, owner; // opensocial ids
var prefs = new gadgets.Prefs();
var lang = prefs.getLang();
var favicon = new Array();
favicon["fav1"] = [ "http://maps.google.com/mapfiles/kml/pal2/icon55.png" , 
				    "http://maps.google.com/mapfiles/kml/pal2/icon55s.png",
					prefs.getMsg("restaurant")];

google.load("maps", "2", {"language" : lang});

// Load avatars images
function loadAvatars() {
var avatars = [
	"aquaman_48",
	"avp1_48",
	"avp2_48",
	"Axel_48",
	"beatles1_48",
	"beatles2_48",
	"beatles3_48",
	"beatles4_48",
	"bender_48",
	"boo_48",
	"C3PO_48",
	"ccf2_48",
	"ccf3_48",
	"ccf4_48",
	"Chaparron_48",
	"Chapulin_48",
	"Chavo_48",
	"Chompiras_48",
	"Darth_Vader_48",
	"default",
	"dragonball2_48",
	"dragonball3_48",
	"dragonball4_48",
	"Dr_Chapatin_48",
	"Duff_McKagan_48",
	"frai_48",
	"harrypotter1_48",
	"harrypotter4_48",
	"harrypotter5_48",
	"kiss1_48",
	"kiss4_48",
	"leela_48",
	"lion-O_48",
	"luigui_48",
	"mario_48",
	"mortalkombat2_48",
	"mortalkombat3_48",
	"mortalkombat4_48",
	"mortalkombat5_48",
	"Mumm-ra_48",
	"nibble_48",
	"Pantro_48",
	"powerranger_48",
	"profesor_farsnworth_48",
	"ptf1_48",
	"ptf4_48",
	"ptf5_48",
	"R2-D2_48",
	"Slash_48",
	"smurf1_48",
	"smurf2_48",
	"smurf3_48",
	"smurf4_48",
	"spiderman_48",
	"Steven_Adler_48",
	"superman_48",
	"tygra_48",
	"wonderwoman_48",
	"yoda_48"
  ];

  var av_html = "";
  for (var i = 0; i < avatars.length ; i++ ) {
	  av_html += "<a href=\"javascript:selectAvatar('" + avatars[i] + "')\" class=\"avatar\">";
	  av_html += "<img src=\"http://os-neighborhood.googlecode.com/svn/trunk/images/avatar/" + 
	  			 avatars[i] + ".png\" border=\"0\"></a>\n";
  }
  document.getElementById("avatarPanel").innerHTML = av_html;
}
 
function selectAvatar(avatar) {

	var req = opensocial.newDataRequest();
  	req.add(req.newUpdatePersonAppDataRequest('VIEWER', "avatar", avatar));
  	req.send();
	g_avatar = avatar;
	document.getElementById("currentAvatar").innerHTML = 
		"<img src=\"http://os-neighborhood.googlecode.com/svn/trunk/images/avatar/" + 
		g_avatar + ".png\" border=\"0\">";
	
	// Save user activity
	var params = {};
	if (owner.getField(opensocial.Person.Field.GENDER).getKey() == 'FEMALE') {
		params[opensocial.Activity.Field.TITLE] = prefs.getMsg("change_her_image");
	} else {
		params[opensocial.Activity.Field.TITLE] = prefs.getMsg("change_his_image");
	}
	var html = '';
	html += '<span style=\'float:left; width: 80px; height: 59px; border: thin solid #9BB4F4; text-align: center;\'>';
	html += '<img src=\'http://os-neighborhood.googlecode.com/svn/trunk/images/update/' + g_avatar + '.png\' border=\'0\'>';
	html += '</span>';
	html += '<span style=\'float:left, padding:20px\'>';
	html += '<b>' + prefs.getMsg("my_place") + ':</b><br>';
	html += g_addr;
	html += '</span>';

	params[opensocial.Activity.Field.BODY] = html;
  	var activity = opensocial.newActivity(params);
	    opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH);
    try { 
    } catch(e) {
    }
	updateMap();

}

// Map initialization in canvas view
function initMapCanvas() {

	loadAvatars();
	// Check viewer has app
	var viewer_app = false;
	if ((gadgets.util.getUrlParameters()["gadgetViewer"])) {
		viewer_app = true;
	}
	
	if (viewer_app) {
		// Load opensocial parameters
		var req = opensocial.newDataRequest();
		
		var opt_params = { };
		opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
			opensocial.Person.Field.ADDRESSES,
			opensocial.Person.Field.PROFILE_URL,
			opensocial.Person.Field.GENDER,
			opensocial.Person.Field.ABOUT_ME,
			opensocial.Person.Field.FASHION,
			opensocial.Person.Field.HAPPIEST_WHEN,
			opensocial.Person.Field.JOB_INTERESTS,
			opensocial.Person.Field.PETS
			];
	
		req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER, opt_params), "viewer"); 
		req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER, opt_params), 'owner');
		req.add(req.newFetchPersonAppDataRequest('VIEWER', "avatar"), "viewer_avatar");
		req.send(
				function get_callback(response) {
					viewer = response.get("viewer").getData();
					owner  = response.get("owner").getData();
	
					// Set tags for adsense
					var htmlTags = document.getElementById("tags");
					htmlTags.innerHTML = viewer.getField(opensocial.Person.Field.ABOUT_ME) + ", ";
					htmlTags.innerHTML += viewer.getField(opensocial.Person.Field.FASHION) + ", ";
					htmlTags.innerHTML += viewer.getField(opensocial.Person.Field.HAPPIEST_WHEN) + ", ";
					htmlTags.innerHTML += viewer.getField(opensocial.Person.Field.JOB_INTERESTS) + ", ";
					htmlTags.innerHTML += viewer.getField(opensocial.Person.Field.PETS) + ", ";

					// Load current avatar
					var av_data = response.get('viewer_avatar').getData();
					if (typeof(av_data[viewer.getId()]) == 'undefined') {
						g_avatar = 'default';
					} else {
						g_avatar = av_data[viewer.getId()]['avatar'];
					}
					document.getElementById("currentAvatar").innerHTML = 
						"<img src=\"http://os-neighborhood.googlecode.com/svn/trunk/images/avatar/" + 
			  			 g_avatar + ".png\" border=\"0\">";

					
					// Create side bar control
					sidebarDiv = document.getElementById("sidebarfriends");
				
					// Create map
					bounds = '';
					bounds = new google.maps.LatLngBounds();
					map = new google.maps.Map2(document.getElementById("map"));
					map.addControl(new google.maps.LargeMapControl());
					map.addControl(new google.maps.MapTypeControl());
					map.addMapType(G_SATELLITE_3D_MAP);
					map.enableScrollWheelZoom();
					map.setCenter(new google.maps.LatLng(0, 0));
					updateMap();
					// adsense
					var ads_opts = {
									maxAdsOnMap: 2,
									channel: "3031267193"
									};
					var adsManager = new google.maps.AdsManager(map, "ca-pub-8076980071227848", ads_opts);
					//adsManager.enable();
				}
				);
	} else { 
		// Same map as profile view
		// Load opensocial parameters
		var req = opensocial.newDataRequest();
		
		var opt_params = { };
		opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
			opensocial.Person.Field.ADDRESSES,
			opensocial.Person.Field.PROFILE_URL,
			opensocial.Person.Field.GENDER
			];
	
		req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER, opt_params), 'owner');
		req.send(
				function get_callback(response) {
					owner  = response.get("owner").getData();
	
					// Create map
					bounds = '';
					bounds = new google.maps.LatLngBounds();
					map = new google.maps.Map2(document.getElementById("map"));
					map.setMapType(G_NORMAL_MAP);
					map.addControl(new google.maps.LargeMapControl());
					map.enableScrollWheelZoom();
					map.setCenter(new google.maps.LatLng(0, 0));
					// adsense
					updateProfileMap();
					var ads_opts = {
									mode: "experimental",
									maxAdsOnMap: 2,
									channel: "8775198914"
									};
					var adsManager = new google.maps.AdsManager(map, "ca-pub-8076980071227848", ads_opts);
					//adsManager.enable();
				}
				);		
		var footer = document.getElementById("footer");
		footer.innerHTML = '<center>' + prefs.getMsg("need_install") + '</center>';
	}
}


// Map initialization in profile view
function initMapProfile() {

	// Load opensocial parameters
	var req = opensocial.newDataRequest();
	
	var opt_params = { };
	opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
		opensocial.Person.Field.ADDRESSES,
		opensocial.Person.Field.PROFILE_URL,
		opensocial.Person.Field.GENDER
		];

	req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER, opt_params), 'owner');
	req.send(
			function get_callback(response) {
				owner  = response.get("owner").getData();

				// Create map
				bounds = '';
				bounds = new google.maps.LatLngBounds();
				map = new google.maps.Map2(document.getElementById("mapprofile"));
				map.setMapType(G_NORMAL_MAP);
				map.addControl(new google.maps.LargeMapControl());
				map.enableScrollWheelZoom();
				map.setCenter(new google.maps.LatLng(0, 0));
				// adsense
				updateProfileMap();
				var ads_opts = {
								mode: "experimental",
								maxAdsOnMap: 2,
								channel: "8775198914"
								};
				var adsManager = new google.maps.AdsManager(map, "ca-pub-8076980071227848", ads_opts);
				//adsManager.enable();
			}
			);				
}

// Get coordinates by address for favorites
function getFav(favform) {
	
	var geocoder;
	// Geocoder object
    geocoder = new GClientGeocoder();

    var address = gadgets.util.escapeString(document.forms[favform].address.value);
		
	// Get Results
    geocoder.getLocations(address, 
		function getGeoResult(result) {
		
			var resultMsg = document.getElementById("favGeoMsg");
			resultMsg.innerHTML = "";
			
			// Check is valid
			if (!result || result.Status.code != G_GEO_SUCCESS) {
				resultMsg.innerHTML += prefs.getMsg("noResultFound");	
			} else {		
				// Get result number
				var result_count = result.Placemark.length;
				
				if (result_count > 1) {
					resultMsg.innerHTML += prefs.getMsg("moreThanOneFound");
				}
				// Set address on Map
				setfavPoint(result.Placemark[0], favform);
			}
		}
	);  // end getLocations Functions
}

function setfavPoint(placemark, favform) {
	
	// Custom Icon
	var baseIcon = new GIcon();
        baseIcon.iconSize=new GSize(32,32);
        baseIcon.shadowSize=new GSize(56,32);
        baseIcon.iconAnchor=new GPoint(16,32);
        baseIcon.infoWindowAnchor=new GPoint(16,0);
    var custom = new GIcon(baseIcon, favicon[favform][0], null, 
								   favicon[favform][1]);
      
	var point = new google.maps.LatLng(placemark.Point.coordinates[1], placemark.Point.coordinates[0]);
	var mark = new google.maps.Marker(point, {icon: custom, draggable: true});
	
	// Centralize map on address	
	map.setCenter(point, 16);
	// Add Marker
	map.addOverlay(mark);

	var favName = gadgets.util.escapeString(document.forms[favform].name.value);
	// Set html info
	var html;
	html  = "<div id=\"markinfo\">";
	html += "<p><b>" + favicon[favform][2] + ": </b>" + favName + "</p>";
	html += "<p><b>" + prefs.getMsg("address") + ": </b>" + placemark.address + "</p><br>";
	html += "<input name=\"saveLocal\" type=\"button\" value=\"" + prefs.getMsg("button_save_favorite") + "\" onclick=\"setFav('" +  favform + "','" + mark.getPoint().lat() + "','" + mark.getPoint().lng() + "','" + favName + "','" + placemark.address + "'); return false;\">";
	html += "</div>";
	mark.openInfoWindowHtml(html);  
	
	// Marker Events
	google.maps.Event.addListener(mark, "click", function() {
        										   mark.openInfoWindowHtml(html);
     											 });
	google.maps.Event.addListener(mark, "dragstart", function() {
													   map.closeInfoWindow();
													 });

	google.maps.Event.addListener(mark, "dragend", function() {
												     mark.openInfoWindowHtml(html);
 													 g_point[0] = mark.getPoint().lat();
													 g_point[1] = mark.getPoint().lng();
												   });

	// Save user activity
	var params = {};
	params[opensocial.Activity.Field.TITLE] = prefs.getMsg("rec_new_place");
	var html = '';
	html += '<span style="float:left">';
	html += '<img src=\'' + favicon[favform][0] + '\' style="border: thin solid #9BB4F4" />';
	html += '</span>';
	html += '<span style="float:left, padding:20px">';
	html += '<b>' + prefs.getMsg("rec_place") + ':</b><br>';
	html += "<p><b>" + favicon[favform][2] + ": </b>" + favName + "</p>";
	html += "<p><b>" + prefs.getMsg("address") + ": </b>" + placemark.address + "</p><br>";
	html += '</span>';
	params[opensocial.Activity.Field.BODY] = html;
  	var activity = opensocial.newActivity(params);
    try { 
	    opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH);
    } catch(e) {
    }
}
	
function setFav(favform, lat, lng, favName, address) {

	var favobj = {type: favform, lat: lat, lng: lng, name: favName, address: address};
	var favorite = {};
	favorite[favform] = favobj;
	var json = gadgets.json.stringify(favorite);

	// Save Favorites
	var req = opensocial.newDataRequest();
	req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, 'favorites', json));
	req.send();

	updateMap();

}

function consistCheckBox() {
	
	var cform = document.forms["checkOpts"].elements;
	for (var i in cform) {
		if (cform[i].type == 'checkbox') {
			if (cform[i].checked == 'true') {
				show(cform[i].name);
			} else {
				hide(cform[i].name);
			}
		}
	}
}

// a checkbox has been clicked
function boxclick(box,category) {
	if (box.checked) {
		show(category);
	} else {
		hide(category);
	}
}

// shows all markers of a particular category
function show(category) { 
	for (var i in markers) {
		if (markers[i].mycategory == category) {
			markers[i].show();
		}
	}
}

// hides all markers of a particular category
function hide(category) {
	for (var i in markers) {
		if (markers[i].mycategory == category) {
			markers[i].hide();
		}
	}
	// == close the info window, in case its open on a marker that we just hid
	map.closeInfoWindow();
}

// Get coordinates by address
function getGeo() {
		
	var geocoder;
	// Geocoder object
    geocoder = new GClientGeocoder();

    var address = gadgets.util.escapeString(document.forms["geoForm"].address.value);
	
	// Get Results
    geocoder.getLocations(address, 
		function getGeoResult(result) {
		
			var resultDiv = document.getElementById("geosearchresult");
			resultDiv.innerHTML = "";
			
			// Check is valid
			if (!result || result.Status.code != G_GEO_SUCCESS) {
				resultDiv.innerHTML += "<p>" + prefs.getMsg("place_not_found") + "<b>" + address + "</b>.<\p>";
				resultDiv.innerHTML += "<p>" + prefs.getMsg("sugestions") + ":";
				resultDiv.innerHTML += "<ul>";
				resultDiv.innerHTML += "<li>" + prefs.getMsg("not_found_tip_1") + "</li>";
				resultDiv.innerHTML += "<li>" + prefs.getMsg("not_found_tip_2") + "</li>";
				resultDiv.innerHTML += "<li>" + prefs.getMsg("not_found_tip_3") + "</li>";
				resultDiv.innerHTML += "</ul></p>";						
			} else {
		
				// Get result number
				var result_count = result.Placemark.length;
				
				if (result_count > 1) {
					
					resultDiv.innerHTML += prefs.getMsg("places_found_1") + " " + result_count + " " + prefs.getMsg("places_found_2") + "<br />";
					resultDiv.innerHTML += prefs.getMsg("choose_place");
					resultDiv.innerHTML += "<br />";
					resultDiv.innerHTML += "<ul>";
					
					for (var i = 0; i < result_count; i++) {
						resultDiv.innerHTML += "<li><a href='javascript:setUniqueResult(\"" + result.Placemark[i].address + "\")'>" + 
												result.Placemark[i].address + "</a>";	
					}
					resultDiv.innerHTML += "</p>";
					resultDiv.innerHTML += "</ul>";					
				} else {
					
					// Set address on Map
					setMapResult(result.Placemark[0]);
				}
			}
		}
	);  // end getLocations Functions
	//gadgets.window.adjustHeight();
}

// Set unique coordinate result
function setUniqueResult(address) {
	
	document.forms["geoForm"].address.value = address;
	getGeo();
	
}

// Set result on global map
function setMapResult(placemark) {
	
	// Custom Icon
	var baseIcon = new GIcon();
        baseIcon.iconSize=new GSize(32,32);
        baseIcon.shadowSize=new GSize(56,32);
        baseIcon.iconAnchor=new GPoint(16,32);
        baseIcon.infoWindowAnchor=new GPoint(16,0);
    var home = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon56.png", null, 
								   "http://maps.google.com/mapfiles/kml/pal3/icon56s.png");
      
	var point = new google.maps.LatLng(placemark.Point.coordinates[1], placemark.Point.coordinates[0]);
	var mark = new google.maps.Marker(point, {icon: home, draggable: true});
	
	// Centralize map on address	
	map.setCenter(point, 16);
	// Add Marker
	map.addOverlay(mark);

	// Set html info
	var html;
	html  = "<div id=\"markinfo\">";
	html += "<p><b>" + prefs.getMsg("my_place") + ":</b><br \>" + placemark.address + "</p>";
	html += "<input name=\"saveLocal\" type=\"button\" value=\"" + prefs.getMsg("button_save_place") + "\" onclick=\"setLocal(); return false;\">";
	html += "</div>";
	mark.openInfoWindowHtml(html);  
	
	// Marker Events
	google.maps.Event.addListener(mark, "click", function() {
        										   mark.openInfoWindowHtml(html);
     											 });
	google.maps.Event.addListener(mark, "dragstart", function() {
													   map.closeInfoWindow();
													 });

	google.maps.Event.addListener(mark, "dragend", function() {
												     mark.openInfoWindowHtml(html);
 													 g_point[0] = mark.getPoint().lat();
													 g_point[1] = mark.getPoint().lng();
												   });
	g_addr = placemark.address;
	g_point[0] = point.lat();
	g_point[1] = point.lng();
	
}

function setLocal() {
	// Save local in opensocial
	var req = opensocial.newDataRequest();
  	req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, "mapsaddress", g_addr));
  	req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, "mapspoint0", g_point[0]));
  	req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, "mapspoint1", g_point[1]));
  	req.send();
	// Save user activity
	var params = {};
	if (owner.getField(opensocial.Person.Field.GENDER).getKey() == 'FEMALE') {
		params[opensocial.Activity.Field.TITLE] = prefs.getMsg("change_her_place");
	} else {
		params[opensocial.Activity.Field.TITLE] = prefs.getMsg("change_his_place");
	}
	var update_map = 'http://maps.google.com/staticmap?size=75x50&zoom=15&markers=' + 
					 g_point[0] + ',' + g_point[1] +
					 ',blue&key=ABQIAAAAyQfGMjnnYZ7zHMz1QT6m4xTPMcF7qBTxZIQYXGWXKXMGKEZqqxTU3ToRepM_l5y3l6oRHGH6U7TRfg';
	update_map = 'http://os-neighborhood.googlecode.com/svn/trunk/images/app_update.gif';
	var html = '';
	html += '<span style="float:left">';
	html += '<img src=\'' + update_map + '\' style="border: thin solid #9BB4F4" />';
	html += '</span>';
	html += '<span style="float:left, padding:20px">';
	html += '<b>' + prefs.getMsg("new_place") + ':</b><br>';
	html += g_addr;
	html += '</span>';
	params[opensocial.Activity.Field.BODY] = html;
  	var activity = opensocial.newActivity(params);
    try { 
	    opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH);
    } catch(e) {
    }

	updateMap();
}

function resetLocal() {
	
	if (window.confirm(prefs.getMsg("confirm_erase"))) {
		// Reset all data
		var req = opensocial.newDataRequest();
		req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, "mapsaddress", ""));
		req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, "mapspoint0", ""));
		req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, "mapspoint1", ""));
		req.send();
		updateMap();
	}
}

function search_address(addr) {
	var found = false;
	var geocoder;
	// Geocoder object
	geocoder = new GClientGeocoder();
	geocoder.getLocations(addr, 
		function getGeoResult(result) {
			if (result && result.Status.code == G_GEO_SUCCESS) {
				if (result.Placemark.length == 1)
					g_addr = result.Placemark[0].address;
					var point = new google.maps.LatLng(
										result.Placemark[0].Point.coordinates[1], 
										result.Placemark[0].Point.coordinates[0]);
					g_point[0] = point.lat();
					g_point[1] = point.lng();
					found = true;
			}
		});
	return found;
}

function updateMap() {

	// Remove all marks
	map.clearOverlays();
	
	// Reset side bar
	sidebarDiv.innerHTML = '<a href="javascript:setClick(\'' + viewer.getId() + '\')">' + prefs.getMsg("my_place") + '</a><hr>';
	sidebarDiv.innerHTML += '<b>' + prefs.getMsg("friends_list") + '</b><br>';
	
	// Check which type of map info must be loaded
	// Show my friends locals and my local
	if (viewer.getId() == owner.getId()) {
		// Open local search
		//document.getElementById('geosearchbody').style.display = 'block';
		
		// Load my friends locals
		var viewer_friends;
		var req = opensocial.newDataRequest();
		
		var opt_params = { };
		opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
			opensocial.Person.Field.PROFILE_URL
			];
		
		opt_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 500;
		opt_params[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.HAS_APP;
		opt_params[opensocial.DataRequest.PeopleRequestFields.SORT_ORDER] = opensocial.DataRequest.SortOrder.NAME;

		req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, opt_params), "viewer_friends");
		req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, "mapsaddress"), "get_address");
		req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, "mapspoint0"), "get_point0");
		req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, "mapspoint1"), "get_point1");
		req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, "avatar"), "get_avatar");
		req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, "favorites"), "get_favorites");
		req.send(
				function get_callback(response) {
					viewer_friends = response.get("viewer_friends").getData();
					var ad_data = response.get('get_address').getData();
					var pt_data0 = response.get('get_point0').getData();
					var pt_data1 = response.get('get_point1').getData();
					var av_data = response.get('get_avatar').getData();
					var fav_data = response.get('get_favorites').getData();
					
					viewer_friends.each(
							function(person) {
								if (ad_data[person.getId()] &&  ad_data[person.getId()]['mapsaddress'] != null) {
									var address = ad_data[person.getId()]['mapsaddress'];
									var point = [];
									point[0] = pt_data0[person.getId()]['mapspoint0'];
									point[1] = pt_data1[person.getId()]['mapspoint1'];		
									var mark_point = new google.maps.LatLng(point[0], point[1]);
									var avatar;
									if (typeof(av_data[person.getId()]) == 'undefined') {
										avatar = 'default';
									} else {
										avatar = av_data[person.getId()]['avatar'];	
									}
									// Insert a mark point in the map
									insertMarkPoint(mark_point, address, person, true, avatar);
									}
									
									// insert favorite points
									if (typeof(fav_data[person.getId()]) != 'undefined') {
										var friendFavs = gadgets.json.parse(gadgets.util.unescapeString(fav_data[person.getId()]['favorites']));
										for (index in friendFavs) {
											insertFavPoint(person, friendFavs[index]);
										} 
									}									
							}
						);
				}
				);
		
		// Load my local
		var req = opensocial.newDataRequest();
		req.add(req.newFetchPersonAppDataRequest(viewer.getId(), "mapsaddress"), "get_address");
		req.add(req.newFetchPersonAppDataRequest(viewer.getId(), "mapspoint0"), "get_point0");
		req.add(req.newFetchPersonAppDataRequest(viewer.getId(), "mapspoint1"), "get_point1");
		req.add(req.newFetchPersonAppDataRequest(viewer.getId(), "avatar"), "get_avatar");
		req.add(req.newFetchPersonAppDataRequest(viewer.getId(), "favorites"), "get_favorites");
		req.send(
				function get_callback(response) {
				  if (!response.hadError()) {
					var ad_data = response.get('get_address').getData();
					var pt_data0 = response.get('get_point0').getData();
					var pt_data1 = response.get('get_point1').getData();
					var av_data = response.get('get_avatar').getData();
					var fav_data = response.get('get_favorites').getData();
					
					if (!ad_data[viewer.getId()] || !ad_data[viewer.getId()]['mapsaddress']) {
						// Try to find a unique place with os-person address
						// Fetch data												
						var addresses = viewer.getField(opensocial.Person.Field.ADDRESSES);
						var country = addresses[0].getField('country');
						var region = addresses[0].getField('region');
						var city = addresses[0].getField('locality');		
						
						var search_addr = '';
						var search_point = '';
						var geoaddr = '';
						var geocoder;
						// Geocoder object
						geocoder = new GClientGeocoder();
						geoaddr = city + ', ' + region + ', ' + country;
						geocoder.getLocations(geoaddr, function getGeoResult(result) {
							if (result && result.Status.code == G_GEO_SUCCESS && result.Placemark.length == 1) {
								search_addr = result.Placemark[0].address;
								search_point = new google.maps.LatLng(
													result.Placemark[0].Point.coordinates[1], 
													result.Placemark[0].Point.coordinates[0]);
								// Save local in opensocial
								var reqsave = opensocial.newDataRequest();
								reqsave.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER,
																		  "mapsaddress", search_addr));
								reqsave.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER,
																		  "mapspoint0", search_point.lat()));
								reqsave.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER,
																		  "mapspoint1", search_point.lng()));
								reqsave.send();
								
								var avatar;
								if (typeof(av_data[person.getId()]) == 'undefined') {
									avatar = 'default';
								} else {
									avatar = av_data[person.getId()]['avatar'];	
								}
								// Insert a mark point in the map
								insertMarkPoint(search_point, search_addr, owner, false, avatar);					
								// Centralize map on address	
								map.setCenter(bounds.getCenter());
								// Set Zoom
								map.setZoom(map.getBoundsZoomLevel(bounds));
							} else {
								toogleGeoSearch();
								var resultDiv = document.getElementById("geosearchresult");
								resultDiv.innerHTML = "<p><h1>" + prefs.getMsg("new_user_message") + "<\h1><\p>";
							}
						});				
					} else {
						var address = ad_data[viewer.getId()]['mapsaddress'];
						var point = [];
						point[0] = pt_data0[viewer.getId()]['mapspoint0'];
						point[1] = pt_data1[viewer.getId()]['mapspoint1'];
						var mark_point = new google.maps.LatLng(point[0], point[1]);
						var avatar;
						if (typeof(av_data[viewer.getId()]) == 'undefined') {
							avatar = 'default';
						} else {
							avatar = av_data[viewer.getId()]['avatar'];	
						}
						// Insert a mark point in the map
						insertMarkPoint(mark_point, address, owner, false, avatar);						
						
						// insert favorite points
						if (typeof(fav_data[owner.getId()]) != 'undefined') {
							var ownerFavs = gadgets.json.parse(gadgets.util.unescapeString(fav_data[owner.getId()]['favorites']));
							for (index in ownerFavs) {
								insertFavPoint(owner, ownerFavs[index]);
							}
						}
									
						// Centralize map on address	
						map.setCenter(bounds.getCenter());
						// Set Zoom
						map.setZoom(map.getBoundsZoomLevel(bounds));
						g_addr = address;
					}
					
				  }
				});	
	}
	// Show only owner local
	else {
		
		// Load owner local
		var req = opensocial.newDataRequest();
		req.add(req.newFetchPersonAppDataRequest(owner.getId(), "mapsaddress"), "get_address");
		req.add(req.newFetchPersonAppDataRequest(owner.getId(), "mapspoint0"), "get_point0");
		req.add(req.newFetchPersonAppDataRequest(owner.getId(), "mapspoint1"), "get_point1");
		req.add(req.newFetchPersonAppDataRequest(owner.getId(), "avatar"), "get_avatar");
		req.send(function get_callback(response) {
					if (!response.hadError()) {
						var ad_data = response.get('get_address').getData();
						var pt_data0 = response.get('get_point0').getData();
						var pt_data1 = response.get('get_point1').getData();
						var av_data = response.get('get_avatar').getData();
						
						if (ad_data[owner.getId()]) {
							var address = ad_data[owner.getId()]['mapsaddress'];
							var point = [];
							point[0] = pt_data0[owner.getId()]['mapspoint0'];
							point[1] = pt_data1[owner.getId()]['mapspoint1'];
							
							var mark_point = new google.maps.LatLng(point[0], point[1]);		
							var avatar;
							if (typeof(av_data[owner.getId()]) == 'undefined') {
								avatar = 'default';
							} else {
								avatar = av_data[owner.getId()]['avatar'];	
							}
							// Insert mark point
							insertMarkPoint(mark_point, address, owner, true, avatar);
						}
					}
				});
		// Load my local
		var req = opensocial.newDataRequest();
		req.add(req.newFetchPersonAppDataRequest(viewer.getId(), "mapsaddress"), "get_address");
		req.add(req.newFetchPersonAppDataRequest(viewer.getId(), "mapspoint0"), "get_point0");
		req.add(req.newFetchPersonAppDataRequest(viewer.getId(), "mapspoint1"), "get_point1");
		req.add(req.newFetchPersonAppDataRequest(viewer.getId(), "avatar"), "get_avatar");
		req.send(
				function get_callback(response) {
				  if (!response.hadError()) {
					var ad_data = response.get('get_address').getData();
					var pt_data0 = response.get('get_point0').getData();
					var pt_data1 = response.get('get_point1').getData();
					var av_data = response.get('get_avatar').getData();
					
					if (!ad_data[viewer.getId()] || !ad_data[viewer.getId()]['mapsaddress']) {
						var address = prefs.getMsg("no_place_message");
						var point = null;
					} else {
						var address = ad_data[viewer.getId()]['mapsaddress'];
						var point = [];
						point[0] = pt_data0[viewer.getId()]['mapspoint0'];
						point[1] = pt_data1[viewer.getId()]['mapspoint1'];
					}

					var mark_point = new google.maps.LatLng(point[0], point[1]);
						
					var avatar;
					if (typeof(av_data[viewer.getId()]) == 'undefined') {
						avatar = 'default';
					} else {
						avatar = av_data[viewer.getId()]['avatar'];	
					}

					// Insert a mark point in the map
					insertMarkPoint(mark_point, address, viewer, false, avatar);
					
					// Centralize map on address	
					map.setCenter(bounds.getCenter());
					// Set Zoom
					map.setZoom(map.getBoundsZoomLevel(bounds));
					g_addr = address;
					
				  }
				});	
	}
}


function updateProfileMap() {
	
					
	// Remove all marks
	map.clearOverlays();
	
	// Load owner local
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonAppDataRequest(owner.getId(), "mapsaddress"), "get_address");
	req.add(req.newFetchPersonAppDataRequest(owner.getId(), "mapspoint0"), "get_point0");
	req.add(req.newFetchPersonAppDataRequest(owner.getId(), "mapspoint1"), "get_point1");
	req.add(req.newFetchPersonAppDataRequest(owner.getId(), "avatar"), "get_avatar");
	req.send(function get_callback(response) {
				if (!response.hadError()) {
					var ad_data = response.get('get_address').getData();
					var pt_data0 = response.get('get_point0').getData();
					var pt_data1 = response.get('get_point1').getData();
					var av_data = response.get('get_avatar').getData();
					
					if (ad_data[owner.getId()]) {
						var address = ad_data[owner.getId()]['mapsaddress'];
						var point = [];
						point[0] = pt_data0[owner.getId()]['mapspoint0'];
						point[1] = pt_data1[owner.getId()]['mapspoint1'];
						
						var mark_point = new google.maps.LatLng(point[0], point[1]);							
						// Centralize map on address	
						map.setZoom(14);
						var avatar;
						if (typeof(av_data[owner.getId()]) == 'undefined') {
							avatar = 'default';
						} else {
							avatar = av_data[owner.getId()]['avatar'];	
						}
						// Insert mark point
						insertMarkPoint(mark_point, address, owner, false, avatar);
						map.setCenter(mark_point);
						setClick(owner.getId());
					}
				}
			});
}

// Insert marker
function insertMarkPoint(point, address, person, sidebar, avatar) {

	// Custom Icon
	icons[person.getId()] = null;
    icons[person.getId()] = new GIcon();
    icons[person.getId()].image = "http://os-neighborhood.googlecode.com/svn/trunk/images/avatar/" + avatar + ".png";
    icons[person.getId()].shadow = "http://os-neighborhood.googlecode.com/svn/trunk/images/avatar/" + avatar + "s.png";
    icons[person.getId()].iconSize = new GSize(48.0, 48.0);
    icons[person.getId()].shadowSize = new GSize(73.0, 48.0);
    icons[person.getId()].iconAnchor = new GPoint(24.0, 24.0);
    icons[person.getId()].infoWindowAnchor = new GPoint(24.0, 24.0);


	markers[person.getId()] = new google.maps.Marker(point, icons[person.getId()]);
	markers[person.getId()].mycategory = "standard";
	// Extend bounds
	bounds.extend(point);
	
	// Add Marker
	map.addOverlay(markers[person.getId()]);
	
	// Set html info
	var html = '';
	html += '<div id="markthumb">';
	html += '<a target="_top" href="' + person.getField(opensocial.Person.Field.PROFILE_URL) 
	     +  '"><img style="border: thin solid #9BB4F4" src="' + person.getField(opensocial.Person.Field.THUMBNAIL_URL) + '"/></a>';
	html += '</div>';
	html += '<div id="markinfo">';
	html += '<a target="_top" href="' + person.getField(opensocial.Person.Field.PROFILE_URL) + '">' + person.getDisplayName() + '</a>';
	html += '<p><b>' + prefs.getMsg("place") + ':</b> ' + address + '</p>';
	html += '</div>';
	// Insert html into ballon
	google.maps.Event.addListener(markers[person.getId()], "click", function() {
        					markers[person.getId()].openInfoWindowHtml(html);
     					 });
	
	if (sidebar) {
		// Add side bar link
		sidebarDiv.innerHTML += '<a href="javascript:setClick(\'' + person.getId() + '\')">' + person.getDisplayName() + '</a><br>';
	}
}

function insertFavPoint(person, favorite) {

	// Custom Icon
    var icon = new GIcon();
    icon.image = favicon[favorite["type"]][0];
    icon.shadow = favicon[favorite["type"]][0];
    icon.iconSize = new GSize(32.0, 32.0);
    icon.shadowSize = new GSize(73480, 32.0);
    icon.iconAnchor = new GPoint(24.0, 24.0);
    icon.infoWindowAnchor = new GPoint(24.0, 24.0);
	// create point
	var point = new google.maps.LatLng(favorite["lat"], favorite["lng"]);
		
	var id = person.getId() + favorite["type"];
	markers[id] = new google.maps.Marker(point, {icon: icon, draggable: true});
	markers[id].mycategory = favorite["type"];
		
	// Add Marker
	map.addOverlay(markers[id]);
	
	// Set html info
	var html = '';
	html += '<div id="markfav">';
	html += prefs.getMsg("recommendedby") + ': <a target="_top" href="' + person.getField(opensocial.Person.Field.PROFILE_URL) 
	     +  '">' + person.getDisplayName() + '</a><br>';
	html += '<b>' + favicon[favorite["type"]][2] + ':</b> ' + favorite["name"] + '<br>';
	html += '<b>' + prefs.getMsg("address") + ':</b> ' + favorite["address"];
	html += '</div>';
	
	// Insert html into ballon
	google.maps.Event.addListener(markers[id], "click", function() {
        					markers[id].openInfoWindowHtml(html);
     					 });
	// show/hide favorites
	consistCheckBox();
}

// Trigger click event on marker
function setClick(id) {
	google.maps.Event.trigger(markers[id], "click");
}

// Send message inviting friends
function inviteFriends() {

	var params = {};
	params[opensocial.Message.Field.TITLE] = prefs.getMsg("invite_title");
	var body = prefs.getMsg("invite_body"); 
	var message = opensocial.newMessage(body, params);
	opensocial.requestSendMessage(opensocial.DataRequest.Group.VIEWER_FRIENDS, message); 
}